import numpy as np
import matplotlib.pyplot as plt
import operator
from os import listdir


def classify0(inX, dataSet, labels, k):
    lineCount = len(dataSet)
    dataSet = np.tile(inX, (lineCount, 1)) - dataSet
    dataSet = dataSet ** 2
    # sum(1)行相加
    disTance = dataSet.sum(axis=1)
    disTance = disTance ** 0.5
    sortedDistanceIndex = disTance.argsort()
    classCount = {}
    for i in range(k):
        label = labels[sortedDistanceIndex[i]]
        classCount[label] = classCount.get(label, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


def img2vector(filename):
    returnVect = np.zeros((1, 1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0, 32 * i + j] = int(lineStr[j])
    return returnVect


def handwritingClassTest():
    hwLables = []
    trainingFileList = listdir('trainingDigits')
    m = len(trainingFileList)
    trainingMat = np.zeros((m, 1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        print(fileNameStr)
        classNumber = int(fileNameStr.split('_')[0])
        hwLables.append(classNumber)
        trainingMat[i, :] = img2vector('trainingDigits/%s' % (fileNameStr))
    testFileList = listdir('testDigits')
    errCount = 0
    mTest = len(testFileList)

    for i in range(mTest):
        fileNameStr = testFileList[i]
        classNumber = int(fileNameStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % (fileNameStr))
        result = classify0(vectorUnderTest, trainingMat, hwLables, 3)
        print("分类结果：%d 真实结果： %d" % (result, classNumber))
        if result != classNumber:
            errCount += 1
    print("共错误：%d，错误率为：%d", (errCount, errCount / mTest))


if __name__ == "__main__":
    handwritingClassTest()
